package com.base.cn.platform.os.service.qa.qareply;

import com.base.cn.platform.os.common.mybatis.BaseBiz;
import com.base.cn.platform.os.common.mybatis.Pagination;
import com.base.cn.platform.os.common.utils.DataUtil;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.common.utils.StringUtils;
import com.base.cn.platform.os.dao.qa.qareply.QaReplyDao;
import com.base.cn.platform.os.entity.qa.qareply.QaReply;
import com.base.cn.platform.os.entity.qa.question.QaQuestion;
import com.base.cn.platform.os.service.manage.user.user.CusUserService;
import com.base.cn.platform.os.service.qa.question.QaQuestionBiz;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 问题评论Biz
 * @author LIZHIPENG
 * @since 2018/4/26
 */
@Service
public class QaReplyBiz extends BaseBiz<QaReply, QaReplyDao> {

    @Autowired
    private CusUserService cusUserService;
    @Autowired
    private QaQuestionBiz qaQuestionBiz;
    @Autowired
    private QaReplyDao qaReplyDao;


    /**
     * 查询问题评论数量
     * @param qaReply 条件
     * @return
     */
    public BigDecimal replyCount(QaReply qaReply){
        String whereSql = getWhereSql(qaReply);
        return this.count(whereSql);
    }

    /**
     * 分页查询问题评论列表
     * @param page 分页
     * @param qaReply 查询条件
     * @param createUserData 是否设置评论学员信息（true：是，false：否）
     * @param childData 是否设置子评论（true：是，false：否）
     * @return
     */
    public PageInfo<QaReply> findQaReplyListPage(QaReply qaReply, Pagination page, boolean createUserData, boolean childData){
        String whereSql = getWhereSql(qaReply);
        PageInfo<QaReply> qaReplyPageInfo = this.findPage(whereSql, page, null);
        qaReplyPageInfo.setList(this.setExtendData(qaReplyPageInfo.getList(), createUserData, childData));
        return qaReplyPageInfo;
    }

    /**
     * 查询问题评论列表（不分页）
     * @param qaReply 查询条件
     * @param createUserData 是否设置评论学员信息
     * @return
     */
    public List<QaReply> findQaReplyList(QaReply qaReply, boolean createUserData, boolean childData){
        String whereSql = getWhereSql(qaReply);
        List<QaReply> qaReplyList = this.find(whereSql, null, null);
        return this.setExtendData(qaReplyList, createUserData, childData);
    }

    /**
     * 保存问题评论
     * @param qaReply
     */
    @Transactional(rollbackFor = IllegalArgumentException.class)
    public void saveQaReply(QaReply qaReply){
        this.save(qaReply);
        QaQuestion question = qaQuestionBiz.findQuestionById(qaReply.getQuestionId(), false, false, false, false, false, false, false);
        QaQuestion _question = new QaQuestion();
        _question.setId(qaReply.getQuestionId());
        _question.setReplyNum(question.getReplyNum() + 1);
        qaQuestionBiz.addOrUpdateQuestion(_question);
    }

    /**
     * 判断用户是否回答过问答
     * @param userId 用户ID
     * @param qaId 问答 ID
     * @return true回复过，false未回复
     */
    public boolean isUserReply(BigDecimal userId,BigDecimal qaId){
        BigDecimal count = this.count(" userId="+userId +" and questionId="+qaId);
        if(count!=null && count.intValue() >1){
           return true;
        }
        return false;
    }

    /**
     * 查询用户回复的问答量
     * @param userId 用户ID
     * @return 回复的问答数量
     */
    public int queryUserReplyQaNum(BigDecimal userId){
        return qaReplyDao.queryUserReplyQaNum(QaReply.class,userId);
    }

    //=========================================
    /**
     * 拼接sql语句
     * @param qaReply 拼接参数
     * @return
     */
    private String getWhereSql(QaReply qaReply){
        StringBuilder whereSql = new StringBuilder(" status != 3");
        if(ObjectUtils.isNotEmpty(qaReply)){
            if(DataUtil.idIsNotNull(qaReply.getQuestionId())){
                whereSql .append( " and questionId=" ).append(qaReply.getQuestionId());
            }
            if(ObjectUtils.isNotEmpty(qaReply.getParentId())){
                whereSql .append( " and parentId=").append( qaReply.getParentId());
            }
            if(StringUtils.isNotEmpty(qaReply.getParentIds())){
                whereSql .append( " and parentId in (").append( qaReply.getParentIds() ).append(")");
            }else if(ObjectUtils.isNotEmpty(qaReply.getStatus())){
                whereSql .append(" and status = ").append( qaReply.getStatus());
            }
        }
        whereSql .append( " order by id desc");
        return whereSql.toString();
    }

    /**
     * 设置扩展数据
     * @param replyList 评论列表
     * @param createUserData 是否设置评论学员信息（true：是，false：否）
     * @return
     */
    private List<QaReply> setExtendData(List<QaReply> replyList, boolean createUserData, boolean childData){
        if(createUserData){
            replyList = this.setUserData(replyList, createUserData);
        }
        if(childData){
            replyList = this.setChildData(replyList, childData, createUserData);
        }
        return replyList;
    }

    /**
     * 设置用户信息
     * @param replyList 评论列表
     * @param createUserData 是否设置评论学员信息（true：是，false：否）
     * @return
     */
    private List<QaReply> setUserData(List<QaReply> replyList, boolean createUserData){
        if(ObjectUtils.isNotEmpty(replyList) && createUserData){
            String userIds = replyList.stream().map(e -> e.getUserId().toString()).distinct().collect(Collectors.joining(","));
            String toUserIds = replyList.stream().map(e -> e.getToUserId().toString()).distinct().collect(Collectors.joining(","));
            String _ids = DataUtil.filterNotNumberStr(userIds + "," + toUserIds);
            Map<BigDecimal, Map<String, Object>> userMap = cusUserService.queryCusUserMapByUserIds(_ids, false, false, false, false, false, false, false);
            for (QaReply qaReply : replyList) {
                qaReply.setUserMap(userMap.get(qaReply.getUserId()));
                qaReply.setToUserMap(userMap.get(qaReply.getToUserId()));
            }
        }
        return replyList;
    }

    /**
     * 为评论列表设置子级评论列表
     * @param replyList 评论列表
     * @param childData 是否设置自己评论列表
     * @param createUserData 是否设置用户信息
     * @return
     */
    private List<QaReply> setChildData(List<QaReply> replyList, boolean childData, boolean createUserData){
        if(ObjectUtils.isNotEmpty(replyList) && childData){
            String parentIds = replyList.stream().map(e -> e.getId().toString()).collect(Collectors.joining(","));
            QaReply qaReply = new QaReply();
            qaReply.setParentIds(parentIds);
            List<QaReply> childList = this.findQaReplyList(qaReply, createUserData, false);
            if(ObjectUtils.isNotEmpty(childList)){
                Map<BigDecimal, List<QaReply>> childListMap = childList.stream().collect(Collectors.groupingBy(QaReply::getParentId));
                for (QaReply reply : replyList) {
                    reply.setChildList(childListMap.get(reply.getId()));
                }
            }
        }
        return replyList;
    }
}
